package revontuli.aMHD.UIhelpers;

import java.util.ArrayList;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import revontuli.aMHD.R;
import revontuli.aMHD.aMHDApp;
import revontuli.aMHD.dataclasses.Stop;
import revontuli.aMHD.*;

public class StopFinderListAdapter extends BaseAdapter implements OnClickListener {
	private ArrayList<Stop> zoznam = new ArrayList<Stop>();
	private Context mContext;

	public StopFinderListAdapter(Context context) {
		this.mContext = context;
	}

	public void fill(ArrayList<Stop> zoznam) {
		if (zoznam.size() > 0) {
			this.zoznam = zoznam;
		} else {
			this.zoznam = new ArrayList<Stop>();
			this.zoznam.add(new Stop(0));
		}
	}

	@Override
	public void onClick(View v) {
		Intent in = new Intent(mContext, StopScheduleAct.class);
		in.putExtra("stopID", (Integer)v.getTag());
		mContext.startActivity(in);
	}

	public int getCount() {
		return zoznam.size();
	}

	public Object getItem(int pos) {
		return zoznam.get(pos);
	}

	public long getItemId(int pos) {
		return pos;
	}

	public View getView(int pos, View mView, ViewGroup mViewGroup) {
		Stop zastavka = zoznam.get(pos);
		
		if (zastavka.id == 0) {
			LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			mView = mInflater.inflate(R.layout.stopfinderitemempty, null);
			
			TextView text = (TextView) mView.findViewById(R.id.stopFinderItemEmptyText);
			text.setText(R.string.nostopsnearby);
			
			return mView;
		}
		
		LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mView = mInflater.inflate(R.layout.stopfinderitem, null);
		
		LinearLayout riadok = (LinearLayout) mView.findViewById(R.id.stopFinderItem);
		riadok.setOnClickListener(this);
		riadok.setTag(zastavka.id);
		
		TextView nazov = (TextView) mView.findViewById(R.id.stopFinderItemName);
		nazov.setText(zastavka.name);
		
		TextView vzdialenost = (TextView) mView.findViewById(R.id.stopFinderItemDistance);

		if (zastavka.distance < 1000) {
			vzdialenost.setText(Integer.toString(zastavka.distance)+" "+ mContext.getResources().getString(R.string.meters));
		} else {
			vzdialenost.setText(Double.toString((double)Math.round(zastavka.distance/100) / 10) + " "+mContext.getResources().getString(R.string.kilometers));
		}
		
		TextView linky = (TextView) mView.findViewById(R.id.stopFinderItemLines);
		String s = aMHDApp.mDataManager.getLinesFromStop(zastavka.id).toString();
		linky.setText(s.substring(1, s.length()-1));
		
		return mView;
	}
}
